/*
 *  Copyright (C) 2010 Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * pn_Summary.java
 *
 * Created on 26/12/2010, 01:34:31
 */
package kuasar.plugin.vmcreator.gui.tooltasks.AddHost;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import kuasar.plugin.vmcreator.utils.Others;
import kuasar.plugin.Intercom.GUI;

/**
 *
 * @author Jesus Navalon i Pastor <jnavalon at redhermes dot net>
 */
public class pn_Summary extends kuasar.plugin.classMod.AbstractPanel {

    protected pn_TB_AddHost toolbar;
    private pn_Name nameDialog = null;
    private pn_Properties properties = null;

    /** Creates new form pn_Summary */
    public pn_Summary(pn_TB_AddHost toolbar) {
        this.toolbar = toolbar;
        properties = new pn_Properties(this, toolbar.data);
        initComponents();
        spn_Summary.getViewport().setOpaque(false);
        spn_Summary.add(properties, null);
        spn_Summary.setViewportView(properties);
        txt_Favorites.setBounds(lbl_Favorites.getBounds());
        txt_Favorites.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btn_Previous = new javax.swing.JButton();
        btn_Next = new javax.swing.JButton();
        btn_Cancel = new javax.swing.JButton();
        spn_Summary = new javax.swing.JScrollPane();
        lbl_Favorites = new javax.swing.JLabel();
        txt_Favorites = new javax.swing.JTextField();

        setOpaque(false);

        btn_Previous.setBackground(new java.awt.Color(0, 0, 0));
        btn_Previous.setForeground(new java.awt.Color(204, 204, 204));
        btn_Previous.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/dialog-previous.png"))); // NOI18N
        btn_Previous.setText("Previous");
        btn_Previous.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Previous.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_PreviousActionPerformed(evt);
            }
        });

        btn_Next.setBackground(new java.awt.Color(0, 0, 0));
        btn_Next.setForeground(new java.awt.Color(204, 204, 204));
        btn_Next.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/save.png"))); // NOI18N
        btn_Next.setText("Save");
        btn_Next.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_NextActionPerformed(evt);
            }
        });

        btn_Cancel.setBackground(new java.awt.Color(0, 0, 0));
        btn_Cancel.setForeground(new java.awt.Color(204, 204, 204));
        btn_Cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/dialog-cancel.png"))); // NOI18N
        btn_Cancel.setText("Cancel");
        btn_Cancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CancelActionPerformed(evt);
            }
        });

        spn_Summary.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Summary.setViewportBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        spn_Summary.setOpaque(false);
        spn_Summary.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                spn_SummaryComponentResized(evt);
            }
        });

        lbl_Favorites.setForeground(new java.awt.Color(204, 204, 204));
        lbl_Favorites.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/star_bl.png"))); // NOI18N
        lbl_Favorites.setText("Add to Favorites");
        lbl_Favorites.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        lbl_Favorites.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                lbl_FavoritesMouseReleased(evt);
            }
        });

        txt_Favorites.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt_FavoritesKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(spn_Summary, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_Favorites)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_Favorites, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
                        .addComponent(btn_Previous)
                        .addGap(6, 6, 6)
                        .addComponent(btn_Next)
                        .addGap(6, 6, 6)
                        .addComponent(btn_Cancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(spn_Summary, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btn_Previous)
                        .addComponent(lbl_Favorites)
                        .addComponent(txt_Favorites, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btn_Next)
                    .addComponent(btn_Cancel))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btn_PreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_PreviousActionPerformed
        toolbar.previous();
}//GEN-LAST:event_btn_PreviousActionPerformed

    private void btn_NextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_NextActionPerformed
        if (nameDialog != null) {
            nameDialog.save();
            return;
        }
        spn_Summary.removeAll();
        nameDialog = new pn_Name(this);
        nameDialog.setBounds(spn_Summary.getBounds());
        spn_Summary.add(nameDialog, null);
        spn_Summary.updateUI();
        nameDialog.focusOnText();
}//GEN-LAST:event_btn_NextActionPerformed

    private void btn_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CancelActionPerformed
        exit();
}//GEN-LAST:event_btn_CancelActionPerformed

    private void lbl_FavoritesMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl_FavoritesMouseReleased
        lbl_Favorites.setVisible(false);
        txt_Favorites.setVisible(true);
        txt_Favorites.requestFocus();
    }//GEN-LAST:event_lbl_FavoritesMouseReleased

    private void txt_FavoritesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_FavoritesKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (txt_Favorites.getText().trim().isEmpty()) {
                txt_Favorites.setVisible(false);
                lbl_Favorites.setVisible(true);
                return;
            }
            if (saveFavorites()) {
                lbl_Favorites.setText("Saved!");
                txt_Favorites.setVisible(false);
                lbl_Favorites.setVisible(true);
                txt_Favorites.setBackground(Color.white);
                lbl_Favorites.setIcon(new javax.swing.ImageIcon(getClass().getResource("/kuasar/plugin/vmcreator/icons/star.png")));
                txt_Favorites.setText("");
                return;
            }
            System.err.println("Virtual Machine couldn't be saved! Check plugins path");
            txt_Favorites.setBackground(Color.pink);
            return;
        }
    }//GEN-LAST:event_txt_FavoritesKeyReleased

    private void spn_SummaryComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_spn_SummaryComponentResized
        properties.setBounds(spn_Summary.getBounds());
    }//GEN-LAST:event_spn_SummaryComponentResized

    protected void exit() {
        toolbar.exit();
    }
    protected void exitReEdit(){
        exit();
        toolbar.panel.restoreList();
    }

    protected void loadSummary() {
        spn_Summary.removeAll();
        properties.setBounds(spn_Summary.getBounds());
        spn_Summary.add(properties, null);
        spn_Summary.updateUI();
    }

    private boolean saveFavorites() {
        String path = ((String) kuasar.plugin.Intercom.ODR.getValue("$PLUGINDIR")) + File.separator + kuasar.plugin.vmcreator.Config.path + File.separator + kuasar.plugin.vmcreator.Config.favorites;
        String filename = txt_Favorites.getText() + ".bin";
        int i = 1;

        while (new File(path + File.separator + filename).exists()) {
            filename = txt_Favorites.getText() + "_" + i + ".bin";
            i++;
        }
        if (saveObject(path + File.separator + filename, toolbar.data)) {
            GUI.launchInfo("Virtual Machine has been saved! ( " + filename + " )");
            toolbar.panel.reloadFavorites();
            return true;
        }
        return false;
    }

    private boolean saveObject(String path, Object data) {
        try {
            FileOutputStream file = new FileOutputStream(path);
            ObjectOutputStream os;
            os = new ObjectOutputStream(file);
            os.writeObject(data);
            os.close();
            file.close();
        } catch (IOException e) {
            System.err.println("Impossible to save Favorites on file \n Cause:" + e.getMessage());
            return false;
        }
        return true;
    }

    protected void save(String name, boolean overwrite) {
        String path = ((String) kuasar.plugin.Intercom.ODR.getValue("$PLUGINDIR")) + File.separator + kuasar.plugin.vmcreator.Config.path + File.separator + kuasar.plugin.vmcreator.Config.virtualmachine;
        File file;
        if (toolbar.filename == null) {
            file = Others.nextFileAvailable(path);
        }else{
            file =new File(path + File.separator + toolbar.filename);
        }

        saveObject(file.getAbsolutePath(), toolbar.data);
        if(!overwrite)
            Others.saveXML(name, file, toolbar.data, toolbar.panel.onAir, true);
        else
            GUI.launchInfo("VM "+ name + " update successfully!");
        toolbar.panel.reloadList();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Cancel;
    private javax.swing.JButton btn_Next;
    private javax.swing.JButton btn_Previous;
    private javax.swing.JLabel lbl_Favorites;
    private javax.swing.JScrollPane spn_Summary;
    private javax.swing.JTextField txt_Favorites;
    // End of variables declaration//GEN-END:variables
}
